package com.whz.gateway.filter;

import com.whz.gateway.common.GatewayMessageAccessor;
import com.whz.gateway.common.constants.FilterOrder;
import com.whz.gateway.common.util.HeaderUtils;
import com.whz.gateway.common.web.GatewayResponseBody;
import com.whz.gateway.user.AuthWrapper;
import com.whz.generic.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.Objects;

/**
 * 登录校验过滤器
 *
 * @author whz
 */
@Slf4j
@Component
public class AuthorizeSignatureFilter extends AbstractGlobalFilter implements Ordered {

    private static final String AUTH_ENABLE = "gateway.authentication.enable";

    @Override
    protected boolean shouldFilter(ServerWebExchange exchange) {
        if (SpringUtils.currentEnvironment().isPresent()) {
            return SpringUtils.currentEnvironment()
                    .get()
                    .getProperty(AUTH_ENABLE, boolean.class, true);
        }
        return false;
    }

    @Override
    protected Mono<Void> apply(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HeaderUtils.TokenInfo token = HeaderUtils.currentToken(request);
        if (Objects.isNull(token) || !validToken(token)) {
            ServerHttpResponse response = exchange.getResponse();
            //当请求不携带Token或者token为空时，直接设置请求状态码为401，返回
            InetSocketAddress remoteAddress = request.getRemoteAddress();
            String clientIp = Objects.requireNonNull(remoteAddress).getAddress().getHostAddress();

            //这条日志应该同步到系统日志中,记录非法的请求
            log.warn("无效token:{}，客户端IP:{}, Access-Path：{}", token, clientIp, request.getPath());

            return GatewayResponseBody.builder()
                    .code(HttpStatus.UNAUTHORIZED.value())
                    .message(HttpStatus.UNAUTHORIZED.name())
                    .path(request.getPath().toString())
                    .method(request.getMethodValue())
                    .timestamp(System.currentTimeMillis())
                    .error(GatewayMessageAccessor.getMessage(
                            "gateway.filter.AccessControlFilter.InvalidToken", token))
                    .build()
                    .sendToResponse(response);
        }

        log.info("current user token :{}", token);

        // save current access token
        HeaderUtils.saveTokenValue(exchange, token);

        return chain.filter(exchange);
    }

    private static boolean validToken(HeaderUtils.TokenInfo token) {
        // 校验token
        if (checkNull(token)) {
            return false;
        }
        switch (token.getBiz()) {
            case API:
                return AuthWrapper.getInstance().validApiToken(token.getToken());
            case USER:
                return AuthWrapper.getInstance().validToken(token.getToken());
            default: {
            }
        }
        return false;
    }

    private static boolean checkNull(HeaderUtils.TokenInfo token) {
        String value = StringUtils.trimWhitespace(token.getToken());
        return StringUtils.isEmpty(value) || "null".equalsIgnoreCase(value);
    }

    @Override
    public int getOrder() {
        return FilterOrder.AUTHORIZATION_ORDER;
    }
}